package cn.iocoder.yudao.module.crm.controller.open.douyin;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "OPEN - 线索")
@RestController
@RequestMapping("/crm/douyin")
@Validated
public class OpenCrmTestController {


    private static final String DOMAIN = "https://open.douyin.com";


    @PostMapping("/test")
    @Operation(summary = "创建线索")
    @OperateLog(enable = false)
    public CommonResult<JSONObject> createClue() {
        String url = "https://open.douyin.com/goodlife/v1/open_api/crm/clue/query/";
        String accessToken = getAccessToken();

        Map<String, Object> data = new HashMap<>();
        data.put("account_id", "7365818580397262857" );
        data.put("end_time", "2024-06-15 00:00:30");
        data.put("page", 1 );
        data.put("page_size", 100);
        data.put("start_time", "2024-01-01 00:00:30");
        ;
        HttpResponse httpResponse = HttpUtil.createGet(url + "?" +HttpUtil.toParams(data)).header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .header("access-token", accessToken)
                .execute()
        ;

        String result = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(result);

        return success(jsonObject);
    }

    private String getAccessToken() {
        String url = "https://open.douyin.com/oauth/client_token/";
        Map<String, Object> data = new HashMap<>();
        data.put("client_key", "awzfx5tthy152oz0");
        data.put("client_secret", "8a09ec7e1f1b892e65c08f5b606ea2dc");
        data.put("grant_type", "client_credential");
        HttpResponse httpResponse = HttpUtil.createPost(url).header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(data)).execute();
        ;
        String result = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getJSONObject("data").getStr("access_token");
    }
}
